package org.example;

/**
 * K个一组翻转链表
 */
public class Solution31 {

    public ListNode reverseKGroup(ListNode head, int k) {
        // 创建一个虚拟头节点，方便操作
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        // 初始化指针
        ListNode prev = dummy;
        ListNode end = dummy;

        while (end.next != null) {
            // 找到当前组的最后一个节点
            for (int i = 0; i < k && end != null; i++) {
                end = end.next;
            }

            // 如果当前组的节点数不足K个，则直接退出循环
            if (end == null) {
                break;
            }

            // 反转当前组的节点
            ListNode start = prev.next; //
            ListNode nextGroup = end.next;
            end.next = null;
            prev.next = reverse(start);
            start.next = nextGroup;

            // 更新指针
            prev = start;
            end = prev;
        }

        // 返回新的头节点
        return dummy.next;
    }

    /**
     * 反转链表的函数
     */
    private ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }

        return prev;
    }

}
